﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;
using System.Windows;

namespace FolderTreeViewer
{
    public class FolderItem : INotifyPropertyChanged // 修复类声明语法错误
    {
        private bool _isExpanded;
        private bool _isSelected;
        public string Name { get; set; }
        public string Path { get; set; }
        public ObservableCollection<FolderItem> Children { get; set; }
        public bool IsExpanded
        {
            get => _isExpanded;
            set
            {
                _isExpanded = value;
                OnPropertyChanged(nameof(IsExpanded));
            }
        }
        public bool IsSelected
        {
            get => _isSelected;
            set
            {
                _isSelected = value;
                OnPropertyChanged(nameof(IsExpanded));
            }
        }
        public FolderItem Parent { get; set; }

        private Lazy<bool> _childrenLoaded;

        public FolderItem(string path, FolderItem parent = null)
        {
            Path = path;
            Parent = parent;
            Children = new ObservableCollection<FolderItem>();
            Name = System.IO.Path.GetFileName(Path); // 使用 Path.GetFileName 提取名称
            _childrenLoaded = new Lazy<bool>(() => LoadChildren(), true);
        }

        private bool LoadChildren()
        {
            if (!Directory.Exists(Path))
                return false;

            try
            {
                string[] directories = Directory.GetDirectories(Path);
                string[] files = Directory.GetFiles(Path);

                foreach (string dir in directories)
                {
                    Children.Add(new FolderItem(dir, this));
                }

                foreach (string file in files)
                {
                    Children.Add(new FolderItem(file, this));
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"无法读取文件夹 {Path}: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            return true;
        }

        public void EnsureChildrenLoaded()
        {
            _ = _childrenLoaded.Value;
        }

        public event PropertyChangedEventHandler PropertyChanged; // 添加 INotifyPropertyChanged 的实现
        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}